#include <stdlib.h>
#include <avr/io.h>
#include <stdint.h>
#include <avr/interrupt.h>
#include "pwm.h"
volatile uint16_t anfang = 0;
volatile uint16_t ende = 0;
volatile uint16_t diff = 0;
volatile uint8_t channel = 0;
volatile uint16_t ocdiff = 0;
volatile uint16_t OCR1Bt = TIMERSTART + 100;
volatile uint16_t OCR1At = TIMERSTART + 3100;                       // 1.5 ms

void pwm_init(void)
{
	PWMDDR &= ~(1 << PWMNR);
  PWMDDR |= (1 << SERVONR);
	PWMPORT |= (1 << PWMNR);
  TCCR1B |= (1 << CS11);          // Prescaler auf 8
  TCNT1 = TIMERSTART;
  OCR1B = OCR1bt;
  TIMSK |= ((1 << TOIE1) | (1 << OCIE1A) | (1 << OCIE1B));          // Timer + OCR Overflow erlauben
	EICRA |= (1 << ISC01);
	EIMSK |= (1 << INT0);
}
ISR(INT0_vect)
{
	if(!(EICRA & (1 << ISC00))){
		anfang = TCNT1;
		EICRA |= (1 << ISC00);
	} else {
		ende = TCNT1;
		EICRA &= ~(1 << ISC00);
		diff = ende - anfang;
		if(channel == 8){channel = 0;}
		if(!(diff > 55)){
		rcdaten[channel] = diff;
		channel++;
		} else {
			channel = 0;
		}
	}
}
ISR(TIMER1_OVF_vect)
{
    cli();
    TCNT1 = TIMERSTART;
    sei();
}
ISR(TIMER1_COMPB_vect)
{
  cli();
  PWMPORT |= (1 << SERVONR);
  OCR1A = 100 + rcdaten[0];
  sei();
}
ISR(TIMER1_COMPA_vect)
{
  cli();
  PWMPORT &= ~(1 << SERVONR);
  sei();
}
